package mo.offer_special;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class L084 {

    private boolean[] visited;

    public List<List<Integer>> permuteUnique(int[] nums) {
        visited = new boolean[nums.length];
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> combination = new ArrayList<>();
        Arrays.sort(nums);
        dfs(res, combination, nums, 0);
        return res;
    }

    private void dfs(List<List<Integer>> res, List<Integer> combination, int[] nums, int index) {
        if (index == nums.length) {
            res.add(new ArrayList<>(combination));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (visited[i] || (i > 0 && nums[i] == nums[i-1] && !visited[i-1])) {
                continue;
            }
            visited[i] = true;
            combination.add(nums[i]);
            dfs(res, combination, nums, index+1);
            combination.remove(combination.size()-1);
            visited[i] = false;
        }
    }

}
